package com.internetCafes.spms.web.sys.controller;

import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.core.annotation.SysLog;
import com.internetCafes.spms.core.exception.RRException;
import com.internetCafes.spms.core.exception.RRExceptionCodeEnum;
import com.internetCafes.spms.core.utils.PageUtils;
import com.internetCafes.spms.core.utils.Query;
import com.internetCafes.spms.core.utils.R;
import com.internetCafes.spms.core.validator.Assert;
import com.internetCafes.spms.web.certificate.entity.EmployeeInfo;
import com.internetCafes.spms.web.certificate.service.EmployeeInfoService;
import com.internetCafes.spms.web.customer.common.cont.CommonConst;
import com.internetCafes.spms.web.sys.form.PasswordForm;
import com.internetCafes.spms.web.sys.form.SysRegisterForm;
import com.internetCafes.spms.web.sys.model.UserInfo;
import com.internetCafes.spms.web.sys.service.UserInfoService;
import com.internetCafes.spms.web.sys.service.UserRoleInfoService;
import com.internetCafes.spms.web.tenant.model.TenantInfo;
import com.internetCafes.spms.web.tenant.service.TenantInfoService;
import com.internetCafes.spms.web.tenant.service.TenantRoleMenuInfoService;
import com.sms.common.util.hutool.core.collection.CollectionUtil;
import com.sms.common.util.hutool.core.util.ObjectUtil;
import com.sms.common.util.hutool.core.util.StrUtil;
import com.sms.common.util.hutool.json.JSONObject;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 系统用户
 *
 * @author Sunny
 * @email rekeeper2011@hotmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRoleInfoService userRoleInfoService;

    @Autowired
    TenantInfoService tenantInfoService;

    @Autowired
    TenantRoleMenuInfoService tenantRoleMenuInfoService;

    @Autowired
    EmployeeInfoService employeeInfoService;

    /**
     * 所有用户列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<UserInfo> userList = userInfoService.queryList(query);
        int total = userInfoService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("/userInfoAndTenantInfo/{userId}")
    public R userInfoAndTenantInfo(@PathVariable("userId") Long userId) {
        UserInfo user = userInfoService.queryObject(userId);
        //获取用户所属的角色列表
        List<Long> roleIdList = userRoleInfoService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);
        Map<String, Object> params = new HashMap<>(16);
        TenantInfo tenantInfos = tenantInfoService.findById(user.getDeptId());
        params.put("orgName", tenantInfos.getTenantName());
        params.put("certificateCode", tenantInfos.getCertificateCode());
        params.put("contact", user.getName());
        params.put("type", user.getType());
        params.put("nickName", user.getNickName());
        params.put("mobile", user.getMobile());
        params.put("email", user.getEmail());
        List<Long> roles = userRoleInfoService.queryRoleIdList(userId);
        params.put("roleIdList", roles);
        params.put("status", user.getStatus());
        params.put("passWord", user.getPassword());
        return R.ok(params);
    }


    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public R info() {
        UserInfo u = ShiroUtils.getUserEntity();
        Map<String, Object> params = new HashMap<>(4);
        u.setPassword("");
        u.setSalt("");
        // 管理层数据设置
        if (ObjectUtil.isNull(u.getManagerFlag())) {
            u.setManagerFlag(CommonConst.FlagEnum.IS.getId());
        }
        params.put("user", u);
        return R.ok(params);
    }


    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @RequestMapping("/password")
    public R password(@RequestBody PasswordForm passwordForm) {
        Assert.isBlank(passwordForm.getNewPassword(), "新密码不为能空");
        UserInfo u = ShiroUtils.getUserEntity();
        //sha256加密
        String password = new Sha256Hash(passwordForm.getPassword(), u.getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(passwordForm.getNewPassword(), u.getSalt()).toHex();

        //更新密码
        int count = userInfoService.updatePassword(u.getId(), password, newPassword);
        if (count == 0) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }


    /**
     * 用户信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        UserInfo user = userInfoService.queryObject(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = userRoleInfoService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        user.setPassword("");
        user.setSalt("");
        return R.ok().put("user", user);
    }


    /**
     * 保存用户
     */
//	@SysLog("保存用户")
//	@RequestMapping("/save")
//	@RequiresPermissions("sys:user:save")
//	public R save(@RequestBody UserInfo user){
//		UserInfo u = userInfoService.queryByTypeAndUserName(user.getType(), user.getName());
//		if(u == null){
//			ValidatorUtils.validateEntity(user, AddGroup.class);
//
//			user.setCreateUserId(ShiroUtils.getUserId());
//			user.setType(user.getRoleIdList().get(0).intValue());
//			userInfoService.save(user);
//		}
//
//		return R.ok();
//	}
    @SysLog("保存用户")
    @PostMapping("/save")
    @RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysRegisterForm registerForm) {
        userInfoService.saveTenantAndDepartmentAndUser(registerForm);
        return R.ok();
        /*if (!IdCardUtils.isValidSocialCreditCode(registerForm.getCertificateCode())) {
            return R.error("社会统一信用代码不正确");
        }

        if (StringUtils.isBlank(registerForm.getPassword())) {
            return R.error("请输入密码");
        }

        Map<String, Object> params = new HashMap<>(4);
        params.put("certificateCode", registerForm.getCertificateCode());
        List<TenantInfo> tenantInfoList = tenantInfoService.query(params);
        if (tenantInfoList != null && tenantInfoList.size() > 0) {
            return R.error("社会统一信用代码已被注册，请勿重复注册");
        }

        params = new HashMap<>(4);
        params.put("name", registerForm.getMobile());
        params.put("deptName", registerForm.getOrgName());
        UserInfo u = userInfoService.queryByOrgNameAndUseName(params);
        if (u == null) {
            userInfoService.saveTenantAndDepartmentAndUser(registerForm);
            return R.ok("注册成功，客服会在2个工作日内与你联系!");
        } else {
            return R.error("手机号已被注册");
        }*/
    }

    @SysLog("添加员工子账号")
    @PostMapping("/employeeSave")
    @RequiresPermissions("certificate:employeeInfo:saveByEmployee")
    public R saveByEmployee(@RequestBody JSONObject json) {
        Long id = Long.valueOf(json.getStr("id"));
        String password = json.getStr("password");
        String colorCode = null;
        if (json.containsKey("colorCode")) {
            colorCode = json.getStr("colorCode");
        }
        Long roleId = null;
        if (json.containsKey("roleId")) {
            roleId = Long.valueOf(json.getStr("roleId"));
        }
        EmployeeInfo employeeInfo = employeeInfoService.findById(id);
        if (StrUtil.isBlank(employeeInfo.getMobile().trim())) {
            throw new RRException(RRExceptionCodeEnum.EMPLOYEE_MOBILE_IS_BLANK);
        }
        Map<String, Object> params = new HashMap<>();
        // params.put("userId", id);
        /*
         * 修改 By zj 2021-10-28
         * 在原有的基础上添加用户子账号条件
         * 这里判断同一租户下只允许一个手机号账户
         * 增加了租户去重判断
         * 修改 By zj 2021-11-30
         * ①-统一企业下一个手机号用户
         * ②-一个员工只会有一个账号
         */
        params.put("nameComplete", employeeInfo.getMobile());
        params.put("deptId", employeeInfo.getTenantId());
        List<UserInfo> userList = userInfoService.queryList(params);
        if (CollectionUtil.isNotEmpty(userList)) {
            return R.error("账号已存在");
        }

        params = new HashMap<>();
        params.put("userId", id);
        userList = userInfoService.queryList(params);
        if (CollectionUtil.isNotEmpty(userList)) {
            return R.error("该员工已存在子账号");
        }
        TenantInfo tenantInfo = tenantInfoService.findById(employeeInfo.getTenantId());
        UserInfo u
                = new UserInfo(employeeInfo.getMobile(), employeeInfo.getName(), password,
                employeeInfo.getMobile(), employeeInfo.getTenantId(), tenantInfo.getTenantName(),
                CommonConstants.UserInfoType.TENANT_CONTANT, employeeInfo.getId());
        u.setTenantId(employeeInfo.getTenantId());
        u.setStatus(CommonConstants.CommonStatus.ENABLE);
        u.setColorCode(colorCode);
        u.setUserId(id);
        userInfoService.save(u);

        // 保留原有逻辑
        List<Long> roleIdList = new ArrayList<>();
        if (ObjectUtil.isNull(roleId)) {
            roleIdList.add(CommonConstants.RoleInfoType.TENANT_CONTACT);
        } else {
            roleIdList.add(roleId);
        }

        userRoleInfoService.saveOrUpdate(u.getId(), roleIdList);
        return R.ok("创建成功");
    }

    /**
     * 修改用户
     */
//	@SysLog("修改用户")
//	@RequestMapping("/update")
//	@RequiresPermissions("sys:user:update")
//	public R update(@RequestBody UserInfo user){
//		ValidatorUtils.validateEntity(user, UpdateGroup.class);
//
//		user.setCreateUserId(ShiroUtils.getUserId());
//		userInfoService.update(user);
//
//		return R.ok();
//	}
    @SysLog("修改用户")
    @PostMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysRegisterForm r) {
        /*if (!IdCardUtils.isValidSocialCreditCode(r.getCertificateCode())) {
            return R.error("社会统一信用代码不正确");
        }*/
        UserInfo user = userInfoService.queryObject(r.getId());
        /* 注释 by zj 2021-12-16 注释，修改账号的时候不对企业信息进行修改
        Long deptId = user.getDeptId();
        TenantInfo tenantInfo = new TenantInfo(r.getOrgName(), r.getCertificateCode(), r.getContact(), r.getMobile());
        tenantInfo.setTenantId(deptId);
        tenantInfoService.update(tenantInfo);*/

        // 登录账号重复校验
        if (!user.getName().equals(r.getContact())) {
            Map<String, Object> params = new HashMap<>();
            params.put("nameComplete", r.getContact());
            params.put("deptId", user.getDeptId());
            List<UserInfo> userInfoListPo = userInfoService.queryList(params);
            if (CollectionUtil.isNotEmpty(userInfoListPo)) {
                throw new RRException(RRExceptionCodeEnum.USER_MOBILE_USED);
            }
        }

        user.setEmail(r.getEmail());
        user.setMobile(r.getMobile());
        user.setNickName(r.getNickName());
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(r.getPassword());
        }
        user.setName(r.getContact());
        if (r.getUserStatus() != null) {
            user.setStatus(Integer.valueOf(r.getUserStatus()));
        }
        user.setRoleIdList(Arrays.asList(r.getRoleIdList()));
        user.setType(r.getType());
        userInfoService.update(user);

        EmployeeInfo employeeInfoDo = employeeInfoService.findById(user.getUserId());
        // 统一手机号与登录账号唯一对应
        employeeInfoDo.setMobile(user.getMobile());
        employeeInfoService.update(employeeInfoDo);
        return R.ok("修改成功");
    }


    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, ShiroUtils.getUserId())) {
            return R.error("当前用户不能删除");
        }

        userInfoService.deleteBatch(userIds);

        return R.ok();
    }


    /**
     * 更新
     */
    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> register(String name, String mobile, String idCard, String address) {

        if (StringUtils.isBlank(name)) {
            return R.error("用户名称不能为空");
        }

        if (StringUtils.isBlank(mobile)) {
            return R.error("手机号不能为空");
        }

        UserInfo u = ShiroUtils.getUserEntity();
        int type = u.getType();

        UserInfo user = null;
        if (!u.getName().equals(mobile)) {
            user = userInfoService.queryByTypeAndUserName(type, mobile);
        }

        if (user == null) {
            user = userInfoService.queryObject(u.getId());
            user.setMobile(mobile);
            user.setName(mobile);
        } else {
            return R.error("手机号已被注册");
        }

        userInfoService.justUpdate(user);
        return R.ok();
    }

}
